package com.nearbymap.model;

import java.util.List;

public class GeocodeResponse implements Address {

	public static final String XPATH_LNG = "GeocodeResponse/result/geometry/location/lng";
	public static final String XPATH_LAT = "GeocodeResponse/result/geometry/location/lat";
	public static final String XPATH_FORMATTED = "GeocodeResponse/result/formatted_address";
	private XmlResponse xmlResponse;

	public GeocodeResponse() {
		xmlResponse = new XmlResponse();
	}
	public GeocodeResponse(String responseXml) {
		xmlResponse = new XmlResponse();
		xmlResponse.setResponseXml(responseXml);
	}
	public GeocodeResponse(XmlResponse xmlResponse) {
		this.xmlResponse = xmlResponse;
	}
	
	public String getFormattedAddress() {
		List<String> list = xmlResponse.getTextAt(XPATH_FORMATTED);
		if(list.size() == 1) {
			return list.get(0);
		} else {
			throw new RuntimeException("Bad FormattedAddress size: " + list.size());
		}
	}

	public LatLng getLatLng() {
		List<String> latList = this.xmlResponse.getTextAt(XPATH_LAT);
		double lat;
		if(latList.size() == 1) {
			lat = Double.parseDouble(latList.get(0));
		} else {
			throw new RuntimeException("Bad LatLng size: " + latList.size());
		}
		List<String> lngList = this.xmlResponse.getTextAt(XPATH_LNG);
		double lng;
		if(lngList.size() == 1) {
			lng = Double.parseDouble(lngList.get(0));
		} else {
			throw new RuntimeException("Bad LatLng size: " + lngList.size());
		}
		return new LatLng(lat, lng);
	}

	public List<String> getTextAt(String xpathPattern) {
		return xmlResponse.getTextAt(xpathPattern);
	}
}
